/** 养猪接口 */
let dateUtil = require('./dateUtil.js');
let {getForJson, postForJson} = require('./jdClient.js');
/** 获取吃完饲料时间 */
function getEatFoodTime() {
    let url = "https://ms.jr.jd.com/gw/generic/uc/h5/m/pigPetLogin";
    let data = {"shareId":"","helpId":"","cardId":"","signId":"","channelLV":"qdy","source":2,"riskDeviceParam":"{\"eid\":\"PYQE3CK2HS2D4GHCZLT2DS4BRDEG3KESNZ65BZEYE4LJMO5OGQS2V2SQBY3GTZKAEFPCYDPS6IHJI22WUU2SPYA23M\",\"dt\":\"Xiaomi\",\"ma\":\"\",\"im\":\"865441031402480\",\"os\":\"android\",\"osv\":\"9\",\"ip\":\"218.20.197.161\",\"apid\":\"JDJR-App\",\"ia\":\"\",\"uu\":\"865441031402480-\",\"cv\":\"5.4.40\",\"nt\":\"WIFI\",\"at\":\"3\",\"fp\":\"a1acce9ae5df5734c5acd89eef9a346c\",\"token\":\"QSFEWZOW7KB5TM7V5O4DDUMGX62TC4C74D4JTMY6PWAO2XUMFGFTVWSY42TFPWBMJRO5EYLESCXVG\"}"};
    data = "reqData=" + encodeURIComponent(JSON.stringify(data));
    let response = postForJson(url, data);
    // log(JSON.stringify(response));
    if (response.resultData && response.resultData.resultCode == 0 
            && response.resultData.resultData.cote && response.resultData.resultData.cote.foodBowl) {
        let resp = response.resultData.resultData;
        let stillTime = resp.cote.foodBowl.stillTime; // 剩余时间
        return stillTime;
    } else {
        console.log('获取小猪吃东西信息失败: ' + JSON.stringify(response));
        return null;
    }
}

/** 查可用饲料 */
function getFoodInfo() {
    let url = "https://ms.jr.jd.com/gw/generic/uc/h5/m/pigPetUserBag?_" + new Date().getTime();
    let data = "reqData=%7B%22category%22%3A%221001%22%2C%22channelLV%22%3A%22qdy%22%2C%22source%22%3A0%2C%22riskDeviceParam%22%3A%22%7B%5C%22eid%5C%22%3A%5C%22%5C%22%2C%5C%22fp%5C%22%3A%5C%227cf236e49bb3e50109451a368a93683b%5C%22%2C%5C%22sdkToken%5C%22%3A%5C%22%5C%22%2C%5C%22fpstep%5C%22%3A%5C%22nb1592643973546%5C%22%7D%22%7D";
    let response = postForJson(url, data);
    // log(response);
    if (response.resultData && response.resultData.resultData && response.resultData.resultData.goods) {
        return response.resultData.resultData.goods;
    } else {
        console.log(response)
    }
    return [];
}

/** 获取库存最大的饲料 */
function getMaxFood() {
    let goods = getFoodInfo();
    let tmpGood = {count: 0, sku: ''};
    goods.forEach(item => {
        if (tmpGood.count < item.count) {
            tmpGood = item;
        }
    });
    return tmpGood;
}

/** 喂食, 返回是否喂食成功 */
function addFood() {
    let food = getMaxFood();
    if (food.count < 20) {
        console.log('养猪:没有超过20的饲料，无法喂养，请收集饲料');
        return false;
    }
    let url = "https://ms.jr.jd.com/gw/generic/uc/h5/m/pigPetAddFood";
    let data = {
        "skuId": food.sku,
        "channelLV": "qdy",
        "source": 0,
        "riskDeviceParam": "{\"eid\":\"SNL6U7JNW7XSS36WPO3EOHKFKRCINPDSPFJCLDBO5QI22KOUU2TAITOW2X2JDFVH6WC35LELNQBFWQ2HHJ4MEMTF5M\",\"fp\":\"9ce300f0682d177d82b1d3958414c465\",\"sdkToken\":\"\",\"token\":\"N72IHJXQL6Z2Q4LQNCEZMFEYIYTIFMIMDEJKJI4Y7GFWLHYWXITB4P2DZPQAD22QTRTRV2FYSEPKM\",\"jstub\":\"XRWAWOQIUIMESQ6TIXWTHYJQVJ2I2CHA776Y47562F55R5SFNZ66KOTBWPSS44RVR33ZXMKCNZJZ4M6IUCVYKAJFMSH567NOZ272WDY\"}"
    }
    let reqData = "reqData=" + encodeURIComponent(JSON.stringify(data));
    let res = postForJson(url, reqData);
    if (res.resultData.resultData && res.resultData.resultData.succesCount > 0) {
        console.log('养猪:喂食成功');
        let stillTime = res.resultData.resultData.cote.foodBowl.stillTime;
        return stillTime;
    } else {
        console.log('养猪:喂食失败:' + JSON.stringify(res));
        return false;
    }
}

/** 获取下一次免费抽奖时间 */
function getNextLucyTime() {
    let url = "https://ms.jr.jd.com/gw/generic/uc/h5/m/pigPetLotteryIndex";
    let data = "reqData=%7B%22category%22%3A%221001%22%2C%22channelLV%22%3A%22qdy%22%2C%22source%22%3A0%2C%22riskDeviceParam%22%3A%22%7B%5C%22eid%5C%22%3A%5C%22%5C%22%2C%5C%22fp%5C%22%3A%5C%227cf236e49bb3e50109451a368a93683b%5C%22%2C%5C%22sdkToken%5C%22%3A%5C%22%5C%22%2C%5C%22fpstep%5C%22%3A%5C%22nb1592643973546%5C%22%7D%22%7D";
    let response = postForJson(url, data);
    // log(response);
    if (response.resultData && response.resultData.resultData) {
        return response.resultData.resultData.nextFreeTime;
    } else {
        console.log('未识别到抽奖时间: ' + JSON.stringify(response));
        return null;
    }
}

/** 抽奖 */
function getLuckyFood() {
    let url = "https://ms.jr.jd.com/gw/generic/uc/h5/m/pigPetLotteryPlay";  
    let data = {
        "source": 0,
        "channelLV": "qdy",
        "riskDeviceParam": "{\"eid\":\"SNL6U7JNW7XSS36WPO3EOHKFKRCINPDSPFJCLDBO5QI22KOUU2TAITOW2X2JDFVH6WC35LELNQBFWQ2HHJ4MEMTF5M\",\"fp\":\"9ce300f0682d177d82b1d3958414c465\",\"sdkToken\":\"\",\"token\":\"F7M6R34ENQGIFZWYT5L6UZEYDR7RJWQ4NXC2HNNU6UGB5I6BXBPA23JWBQHMNHESJW5HIKES4OHOC\",\"jstub\":\"7KIEWWL2CTDTKVABMKSQ2SFR4OFQYCN5I6EM3QR5VC5FV4UMKSOYNRGH7MVJX2GL75OGOKRXSD2H2FSD6I5UEDGYZUYYALWTMJ3MLUI\"}"
    }
    let reqData = "reqData=" + encodeURIComponent(JSON.stringify(data));
    let response = postForJson(url, reqData);
    if (response.resultData && response.resultData.resultCode == 0) {
        if (response.resultData.resultData.award && response.resultData.resultData.count > 0) {
            console.log('抽到%s个%s', response.resultData.resultData.count, response.resultData.resultData.name);
        } else if (response.resultData.resultData.nextFreeTime > 0) {
            console.log('下次免费抽奖还有' + response.resultData.resultData.nextFreeTime/1000 + '秒');
        } else {
            console.log('没有抽到奖品');
        }
    } else {
        console.log('抽奖失败: ' + JSON.stringify(response));
    }
}

/**
 * 开盒子，返回是否已经上限
 */
function openBox() {
    let url = "https://ms.jr.jd.com/gw/generic/uc/h5/m/pigPetOpenBox";
    let data = {
        "source": 2,
        "type": 1,
        "t": new Date().getTime(),
        "channelLV": "qdy",
        "riskDeviceParam": "{\"eid\":\"PYQE3CK2HS2D4GHCZLT2DS4BRDEG3KESNZ65BZEYE4LJMO5OGQS2V2SQBY3GTZKAEFPCYDPS6IHJI22WUU2SPYA23M\",\"dt\":\"Xiaomi\",\"ma\":\"\",\"im\":\"865441031402480\",\"os\":\"android\",\"osv\":\"9\",\"ip\":\"218.20.197.161\",\"apid\":\"JDJR-App\",\"ia\":\"\",\"uu\":\"865441031402480-\",\"cv\":\"5.4.40\",\"nt\":\"WIFI\",\"at\":\"3\",\"fp\":\"12592d82a04b621174928fa6a7e756c0\",\"token\":\"WFLR7ZQVEP7UIGIJ5MVQRQ5JTDJW7JTUJKPXSWOYMBHVICES6OS7OW5POFRVAZWNDZ3RV3EKMN7VG\"}"
    };
    data = "reqData=" + encodeURIComponent(JSON.stringify(data));
    let response = postForJson(url, data);
    if (response.resultData && response.resultData.resultData && response.resultData.resultCode == 0) {
        if (response.resultData.resultData.award && response.resultData.resultData.award.count > 0) {
            let name = response.resultData.resultData.award.name;
            let count = response.resultData.resultData.award.count;
            console.log('开盒子得到%s个%s', count, name);
        } else {
            console.log('开盒子没有东西');
        }
        return false;
    } else if (response.resultData.resultCode == 420) {
        console.log('开盒子：' + response.resultData.resultMsg);
        return true;
    } else {
        console.log('开盒子失败: ' + JSON.stringify(response));
        return false;
    }
}

/** 查询签到天数 */
function getSignDay() {
    let url = "https://ms.jr.jd.com/gw/generic/uc/h5/m/pigPetSignIndex";
    let data = {
        "source": 2,
        "channelLV": "qdy",
        "riskDeviceParam": "{\"eid\":\"PYQE3CK2HS2D4GHCZLT2DS4BRDEG3KESNZ65BZEYE4LJMO5OGQS2V2SQBY3GTZKAEFPCYDPS6IHJI22WUU2SPYA23M\",\"dt\":\"Xiaomi\",\"ma\":\"\",\"im\":\"865441031402480\",\"os\":\"android\",\"osv\":\"9\",\"ip\":\"120.230.131.147\",\"apid\":\"JDJR-App\",\"ia\":\"\",\"uu\":\"865441031402480-\",\"cv\":\"5.4.40\",\"nt\":\"WIFI\",\"at\":\"3\",\"fp\":\"0a3f5700db7efbca97dde51899a272d3\",\"token\":\"DGZXOUSVODBN7RUUJ6TTMUEO72UOYLRRZMJUZSVGV32VSUS7VBX5MYQA7QGKD2OV66IBXSSUTHIR6\"}"
    };
    data = "reqData=" + encodeURIComponent(JSON.stringify(data));
    let response = postForJson(url, data);
    if (response.resultData && response.resultData.resultData && response.resultData.resultCode == 0) {
        let result = response.resultData.resultData;
        console.log(JSON.stringify(result.today))
        return result.today;
    } else {
        console.log('查询签到天数失败: ' + JSON.stringify(response));
        return 0;
    }
}

/** 签到 */
function sign() {
    let today = getSignDay();
    // if (hasSign) {
    //     console.log('今日已签到');
    //     return true;
    // }
    let url = "https://ms.jr.jd.com/gw/generic/uc/h5/m/pigPetSignOne";
    let data = {
        "source": 0,
        "no": today,
        "channelLV": "qdy",
        "riskDeviceParam": "{\"eid\":\"SNL6U7JNW7XSS36WPO3EOHKFKRCINPDSPFJCLDBO5QI22KOUU2TAITOW2X2JDFVH6WC35LELNQBFWQ2HHJ4MEMTF5M\",\"fp\":\"9ce300f0682d177d82b1d3958414c465\",\"sdkToken\":\"\",\"token\":\"TUXQCABCXSROELAMIASQYNLTRCLAW3E7JVDUHIMHSQKBTIHDRGF6KPYTTU6ILFTAOP4NKJP7RYBH4\",\"jstub\":\"RM7X6L6FUM56HDSGYAOSRUSMADBOC7I4LQ4I2MAENOLSJRBK7TWRDWYCR7ZL3F474Q3JVLAJ2H2IQ2OBSC4ATKZY3IWXZFW5YXZU6QQ\"}"
    };
    data = "reqData=" + encodeURIComponent(JSON.stringify(data));
    let response = postForJson(url, data);
    console.log(JSON.stringify(response))
    if (response.resultData && response.resultData.resultData && response.resultData.resultCode == 0) {
        let result = response.resultData.resultData;
        if (result.sign) {
            console.log('连续第%s天签到，获得%s个%s', result.today, result.award.count, result.award.name);
        } else {
            console.log('今日已签到');
        }
        return true;
    } else {
        console.log('签到失败: ' + JSON.stringify(response));
        return false;
    }
}

/** 黑名单任务： 不处理 */
const backList = {
    "MC694": "提交信息可获得30g猪粮~（开卡送好礼~）",
    "MC696": "小金库还信用卡满1000元，可获得30g猪粮",
    "MC723": "购买1000元以上的黄金产品，可得80g猪粮",
    "MC806": "下载登陆梨涡APP，认证学生后可得30g猪粮",
    "MC984": "1元购买京惠保百万医疗险，得20g随机粮食",
    "MC985": "1元钱购买药无忧抗癌险，得20g随机粮食",
    "MC1002": "购买90天养老理财产品，可得200g猪粮",
    "MC1006": "购买1个月定期理财产品，可得200g猪粮",
    "MC1007": "购买指定理财产品成功后可得30g猪粮",
    "MC1140": "签到完成后可得5g随机食物",
    "MC1278": "花金贴兑换任意权益，可得20g随机食物",
    "MC1305": "购买任意1张权益卡，可得20g随机食物。",
    "MC737": "购买可得20g随机食物（每月送7元话费券）",
    "MC1168": "买入(预约除外)理财，必得600g随机食物",
    "CPP01": "邀App新用户成功领取新人礼，可得3元红包"
};
/** 获取任务列表 */
function pigPetMissionList() {
    let url = "https://ms.jr.jd.com/gw/generic/uc/h5/m/pigPetMissionList";
    let data = {
        "source": 0,
        "channelLV": "qdy",
        "riskDeviceParam": "{\"eid\":\"\",\"fp\":\"7cf236e49bb3e50109451a368a93683b\",\"sdkToken\":\"\",\"fpstep\":\"nb1593654156105\"}"
    };
    data = "reqData=" + encodeURIComponent(JSON.stringify(data));
    let response = postForJson(url, data);
    if (response.resultCode == 0 && response.resultData && response.resultData.resultData && response.resultData.resultData.missions) {
        // 格式 .status 3：去完成， 4： 可领取奖励
        // 格式 .mid 任务id
        // 格式 .missionName 任务名称
        let missions = response.resultData.resultData.missions;
        // console.log('获取任务列表成功');
        let blackListKeys = Object.keys(backList).join(",");
        missions.forEach(mission => {
            // CPP开头、 MC开头、 CPD开头？
            let mid = mission.mid;
            if (mission.status == 4) {
                if (mission.mid.startsWith('CPD')) {
                    getMissionReward(mid);
                } else if (mission.mid.startsWith('MC')) {
                    console.log("收取任务【" + mid + "】奖励");  
                    doPigPetDoMission(mid);       
                } else if (mission.mid.startsWith('CPP')) {
                    console.log('不支持的自动任务【' + mid + '】');
                } else {
                    console.log('未知的任务【' + mid + '】');
                }
            } else if (mission.status == 3) {
                if (blackListKeys.indexOf(mid) > -1) {
                    // console.log('跳过黑名单任务:【' + mid + '】');
                } else if (mission.mid.startsWith('CPD')) {
                    doPigPetDoMission(mid);
                } else if (mission.mid.startsWith('MC')) {
                    if (mission.missionContent.indexOf('浏览') > -1) {
                        console.log('浏览任务【' + mid + '】：' + mission.missionContent);
                        doBrowseMission(mid);
                        // 无论成功或失败，都尝试收取奖励
                        finishReadMission(missionId);
                    } else {
                        console.log('非浏览任务【' + mid + '】：' + mission.missionContent);
                        doPigPetDoMission(mid);
                    }                 
                } else if (mission.mid.startsWith('CPP')) {
                    console.log('不支持的自动任务【' + mid + '】:' + mission.missionContent);
                } else {
                    console.log('未知的任务【' + mid + '】:' + mission.missionContent);
                }
            }
        });
        return true;
    } else {
        console.log('获取任务列表失败: ' + JSON.stringify(response));
        return false;
    }
}

/** 完成任务（CPD/MC）或领取奖励(MC) */
function doPigPetDoMission(missionId) {
    let url = "https://ms.jr.jd.com/gw/generic/uc/h5/m/pigPetDoMission";
    let data = {
        "source": 0,
        "mid": missionId,
        "channelLV": "qdy",
        "riskDeviceParam": "{\"eid\":\"\",\"fp\":\"7cf236e49bb3e50109451a368a93683b\",\"sdkToken\":\"\",\"fpstep\":\"nb1593654156105\"}"
        // "riskDeviceParam": "{\"eid\":\"PYQE3CK2HS2D4GHCZLT2DS4BRDEG3KESNZ65BZEYE4LJMO5OGQS2V2SQBY3GTZKAEFPCYDPS6IHJI22WUU2SPYA23M\",\"dt\":\"Xiaomi\",\"ma\":\"\",\"im\":\"865441031402480\",\"os\":\"android\",\"osv\":\"9\",\"ip\":\"113.66.255.123\",\"apid\":\"JDJR-App\",\"ia\":\"\",\"uu\":\"865441031402480-\",\"cv\":\"5.4.40\",\"nt\":\"WIFI\",\"at\":\"3\",\"fp\":\"0f481dd8696c4e2fbb6c050382469b72\",\"token\":\"3XI73XYUJ4N5BVCOPACMNX6GRGGIVC6BEEQSGNDZR5ZJNWGNVW3L5CAGBRC7T7K77V2NBZDOFIEM6\"}"
    };
    data = "reqData=" + encodeURIComponent(JSON.stringify(data));
    let response = postForJson(url, data);
    if (response.resultData && response.resultData.resultData && response.resultData.resultData.status) {
        let status = response.resultData.resultData.status;
        if (status == 3) {
            console.log('任务【' + missionId + '】未完成');
        } else if (status == 4) {
            console.log('任务【' + missionId + '】执行成功');
        } else if (status == 5) {
            console.log('任务【' + missionId + '】领取成功');
        } else {
            console.log('执行任务【' + missionId + '】未知结果：' + JSON.stringify(response));
        }
    } else {
        console.log('执行任务【' + missionId + '】失败: ' + JSON.stringify(response));
    }
}

/** 执行浏览任务 */
function doBrowseMission(missionId) {
    // 截取missionId的MC开头标志
    let mid = missionId.substring(2);
    let url = "https://jrmfp.jr.jd.com/hpvuv";
    let data = {
        randomUuid: "62E220039CFC20C6BF993438765548",
        firstPaintTime: "553",
        loadTime: "1272",
        domReadyTime: "625",
        readyStart: "15",
        redirectTime: "0",
        appcacheTime: "0",
        unloadEventTime: "0",
        lookupDomainTime: "0",
        connectTime: "0",
        requestTime: "16",
        initDomTreeTime: "615",
        loadEventTime: "11",
        h5BusinessType: "reporttime",
        url: "https://m.jr.jd.com/member/task/index.html?channel=pig&missionId=" + 347 + "&readTime=5",
        ref: "https://u.jr.jd.com/uc-fe-wxgrowing/cloudpig/index/159384120202248288/?channelLV=qdy&amp%3BshareId=vZoq-O6FkuUp62HuKheuTcAdoUJQ3Dik&amp%3BsourceID=240&amp%3Bactflag=1AEE706F1D&amp%3BisPay=N&amp%3Butm_source=Android%2aurl%2a1593841204607&amp%3Butm_medium=jrappshare&amp%3Butm_term=qqfriends",
        net: "",
        // screen: "375*812",
        // os: "iphone",
        // version: "604.1",
        // browser: "safari/604.1",
        // inplatform: "",
        // userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1",
        // logLevel: "TRACE",
        // title: "任务中心",
        pin: "jd_494844e91c166",
        // sid: "-no sid-",
        // urlO: "https://m.jr.jd.com",
        // urlP: "/member/task/index.html",
        // urlH: "",
        // urlS: "%253Fchannel%253Dpig%2526missionId%253D347%2526readTime%253D5",
    };
    let body = "";
    for (k in data) {
        body += k + "=" + encodeURIComponent(data[k]) + '&';
    }
    let response = postForJson(url, body);
    // log(response)
    if (response.resultCode == 0) {
        console.log('浏览任务浏览成功: 任务id【' + missionId + '】');
        return true;
    } else {
        console.log('浏览任务失败: 任务id【' + missionId + '】' + JSON.stringify(response));
        return false;
    }
}

/** 完成只读任务 */
function finishReadMission(missionId) {
    // 截取missionId的MC开头标志
    let mid = missionId.substring(2);
    let data = {"missionId": mid, readTime: 5}
    let url = "https://ms.jr.jd.com/gw/generic/mission/h5/m/finishReadMission?reqData=" + JSON.stringify(data);
    let response = getForJson(url);
    // console.log(JSON.stringify(response))
    if (response.resultCode == 0 && response.resultData) {
        if (response.resultData.success) {
            console.log('浏览任务领取奖励成功: 任务id【' + missionId + '】');
            return true;
        } else {
            console.log('浏览任务领取奖励失败：任务id【' + missionId + '】' + JSON.stringify(response));
        }
    } else if (response.resultData && response.resultData.code == '0001') {
        console.log('浏览任务已领取奖励: 任务id【' + missionId + '】');
        return true;
    } else {
        console.log('浏览任务领取失败: 任务id【' + missionId + '】' + JSON.stringify(response));
        return false;
    }
}

/** 收取任务奖励 */
function getMissionReward(missionId) {
    let url = "https://ms.jr.jd.com/gw/generic/uc/h5/m/pigPetDoMission";
    let data = {
        "source": 2,
        "mid": missionId,
        "channelLV": "qdy",
        "riskDeviceParam": "{\"eid\":\"PYQE3CK2HS2D4GHCZLT2DS4BRDEG3KESNZ65BZEYE4LJMO5OGQS2V2SQBY3GTZKAEFPCYDPS6IHJI22WUU2SPYA23M\",\"dt\":\"Xiaomi\",\"ma\":\"\",\"im\":\"865441031402480\",\"os\":\"android\",\"osv\":\"9\",\"ip\":\"113.66.254.74\",\"apid\":\"JDJR-App\",\"ia\":\"\",\"uu\":\"865441031402480-\",\"cv\":\"5.4.40\",\"nt\":\"WIFI\",\"at\":\"3\",\"fp\":\"04b271c0b2121470afacfddff4bec5fc\",\"token\":\"3TMRKIDAOQ6RU7EPJSDZQZSPREK2H4NYVOKBXI6DTPGVR4RUK67AOMBBSEZY7GGHCEJO5X5I5FALQ\"}"
    };
    data = "reqData=" + encodeURIComponent(JSON.stringify(data));
    let response = postForJson(url, data);
    if (response.resultData && response.resultData.resultData && response.resultData.resultData.award) {
        let award = response.resultData.resultData.award;
        console.log('收取任务奖励：' + award.name + award.count + '个');
    } else {
        console.log('收取任务奖励失败: ' + JSON.stringify(response));
    }
}

const pigInfo = storages.create("JD-PIG");
function run() {
    console.log("=== 养猪开始 ===");
    let curTime = new Date().getTime();
    // 开盒子
    let openingBox = false;
    // 签到
    let lastSignTime = pigInfo.get("lastSignTime", 0);
    let lastSignTimeFullDay = dateUtil.format(lastSignTime, "yyyyMMdd");
    curFullDay = dateUtil.format(curTime, "yyyyMMdd");
    if (lastSignTimeFullDay != curFullDay) {
        if (sign()) {
            pigInfo.put("lastSignTime", curTime);
        }
    } else {
        console.log('养猪:今天已签到');
    }

    // 抽奖
    let nextFreeTime = pigInfo.get("nextFreeTime", 0);
    if (nextFreeTime == 0 || nextFreeTime <= curTime) {
        let nextFreeTime = getNextLucyTime();// 抽奖
        if (nextFreeTime == 0) {
            console.log('养猪:开始免费抽奖');
            getLuckyFood();
        } else {
            console.log('养猪:等待%s分钟后免费抽奖', nextFreeTime/1000/60);
        }
        pigInfo.put("nextFreeTime", nextFreeTime + curTime);
    } else {
        console.log('养猪:%s后能免费抽奖', dateUtil.format(nextFreeTime, "yyyy-MM-dd HH:mm:ss"));
    }
    
    // 开盒子
    let lastFinishOpenBoxTime = pigInfo.get("lastFinishOpenBoxTime", 0);
    let lastFinishFullDay = dateUtil.format(lastFinishOpenBoxTime, "yyyyMMdd");
    let curFullDay = dateUtil.format(curTime, "yyyyMMdd");
    if (lastFinishFullDay != curFullDay && !openingBox) {
        console.log('养猪:开始开盒子');
        openingBox = true;
        let openBoxTask = setInterval(() => {
            if (openBox()) {
                clearInterval(openBoxTask);
                pigInfo.put("lastFinishOpenBoxTime", curTime);
                console.log('养猪:停止开盒子');
            }
        }, 4000);
    } else {
        // console.log('今天已经限制开盒子了');
    }

    // 喂食
    let eatFinishTime = pigInfo.get("eatFinishTime", 0);
    if (eatFinishTime == 0 || eatFinishTime <= curTime) {
        let stillTime = getEatFoodTime();
        if (stillTime == 0) {
            console.log('养猪:没东西吃了，开始喂食');
            stillTime = addFood();
            // if (addFood()) {
            //     stillTime = getEatFoodTime();
            // }
        } else {
            console.log('养猪:拱白菜中, 还有%s分钟搞定', stillTime/1000/60);
        }
        pigInfo.put("eatFinishTime", curTime + stillTime);
    } else {
        console.log('养猪:拱白菜中, %s吃完', dateUtil.format(eatFinishTime, "yyyy-MM-dd HH:mm:ss"));
    }
    // 任务
    pigPetMissionList();
    console.log("=== 养猪结束 ===");
}

module.exports = {
    run: run
};

// run();
// setTimeout();
// pigPetMissionList();
// sign()
// doBrowseMission('MC347');